﻿Imports System.Data
Imports System.Net
Imports System.IO
Imports System.Text
Imports dooll.Net

Namespace UI
    Public Class Proxy
        Inherits System.Web.UI.Page
        Private web As New dooll.Net.HttpClient

        ''' <summary>
        ''' Cookie容器
        ''' </summary>
        ''' <value>cookiecontainer</value>
        ''' <returns>cookiecontainer</returns>
        ''' <remarks></remarks>
        Public Property Cookies As CookieContainer
            Get
                Return web.Cookies
            End Get
            Set(ByVal value As CookieContainer)
                web.Cookies = value
            End Set
        End Property

        ''' <summary>
        ''' 页面加载
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks></remarks>
        Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            '清除缓存
            Response.CacheControl = "no-cache"
            Response.Expires = -1

            '远程URL
            Dim url As String = Request.QueryString("url"), charset As String = Request.QueryString("charset")
            If String.IsNullOrEmpty(url) Then
                Response.StatusCode = 404
                Response.End()
            End If

            If String.IsNullOrEmpty(charset) Then charset = "utf-8"

            Dim uri As New Uri(url), scheme As String
            scheme = uri.Scheme

            '读取本地的Cookies,加入远程请求
            For i = 0 To Request.Cookies.Count - 1
                Dim c As HttpCookie = Request.Cookies(i)
                web.Cookies.Add(New System.Net.Cookie(c.Name, c.Value, "/", uri.Host))
            Next

            '读取远程返回的数据
            Dim bytes As Byte() = web.DownloadData(uri), body As String = String.Empty, cookies As System.Net.CookieCollection
            body = Encoding.GetEncoding(charset).GetString(bytes)
            cookies = web.Cookies.GetCookies(New System.Uri(String.Concat(scheme, "://", uri.Host)))

            '远程Cookie写入本地
            For Each c As Cookie In cookies
                Dim nc As New HttpCookie(c.Name, c.Value)
                c.Expires = DateTime.Now.AddMinutes(5)
                Response.Cookies.Add(nc)
            Next

            '回显返回值
            Response.Write(body)

        End Sub

    End Class

End Namespace

